package main

import (
	"context"
	"fmt"
	"time"
)

// handle  用来模拟耗时操作（例如，网络请求）
func handle(ctx context.Context, duration time.Duration, deep int) {
	if deep > 0 {
		time.Sleep(200 * time.Millisecond)
		handle(ctx, duration, deep-1)
	}

	select {
	case <-ctx.Done():
		fmt.Printf("%v层handle,context取消，%v\n", deep, ctx.Err())
	case <-time.After(duration):
		fmt.Printf("%v层handle,time取消\n", deep)
	}
}

//1、基于时间的超时
func worker1() {
	deep := 10
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()

	go handle(ctx, 500*time.Millisecond, deep)
	//阻塞主函数不结束。如果主函数超时，这里就会继续执行下去，子函数handle就会直接全部结束
	select {
	case <-ctx.Done():
		fmt.Printf("主worker1函数执行完毕，%v\n", ctx.Err())
	}
}

//2、基于操作的超时
func worker2() {
	deep := 10
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)

	go handle(ctx, 500*time.Millisecond, deep)
	//模拟10s后，手动调用cancel超时
	time.Sleep(10 * time.Second)
	cancel()
}
func main() {
	worker1()
	worker2()
}
